package com.huluobo.a2107jetpackkotlindemo.paging

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import kotlinx.coroutines.flow.Flow

/**
 *  Created by LC on 2023/11/29.
 */
class PagingViewModel : ViewModel() {
    fun getPagingData(): Flow<PagingData<GoodsBean>> {
        return Repo.getPagingData().cachedIn(viewModelScope)
    }
}

object Repo {
    private const val PAGE_SIZE = 5
    private val service = ApiService.create()
    fun getPagingData(): Flow<PagingData<GoodsBean>> {
        //prefetchDistance 表示距离底部多少条数据开始预加载
        //设置为0表示滑动到底部才进行加载,如果不设置,默认值为当前分页大小,也就是pageSize的大小
        //如果想让用户对加载无感,则适当增加这个即可,比如咱们现在设置的5倍大小
        return Pager(
            config = PagingConfig(pageSize = PAGE_SIZE, prefetchDistance = PAGE_SIZE * 5),
            pagingSourceFactory = {
                RepoPagingSource(service)
            }
        ).flow
    }
}